//
//  DrivingLicenseViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2019/2/19.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit
import AipOcrSdk
import IDLFaceSDK

class DrivingLicenseViewController: UIViewController {
    
    var drivingLicenseFn: String?
    
    var drivingLicenseImg : String?           //驾驶证照片
    var drivingLicensePageImg : String?      //驾驶证副页照片
    
    var drivingLicenseIdentifier: String?                 //驾照身份证号码
    
    @IBOutlet weak var numberTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        numberTextField.text = drivingLicenseFn
    }
    
    @IBAction func drivingLicense(_ sender: UIButton) {
        let vc = AipGeneralVC.viewController { [weak self] image in
            
            guard let self = self else {
                return
            }
            
            guard let image = image else {
                XHProgressHUD.showError("图片为空")
                return
            }
            
            self.dismiss(animated: true, completion: nil)
            
            sender.setImage(image, for: .normal)
            
            //上传图片
            User.uploadFile(image) { [weak self] imagePath in
                self?.drivingLicenseImg = imagePath
            }
            
            JZLoading.showLoadingWith(toView: self.view)
            AipOcrService.shard()?.detectDrivingLicense(from: image, withOptions: nil, successHandler: { [weak self] result in
                
                DispatchQueue.main.async {
                    JZLoading.hideLoading()
                }
                
                let a = (((result as AnyObject)["words_result"] as? [String : Any])!["证号"] as AnyObject)["words"]
                if let b = a as? String {
                    self?.drivingLicenseIdentifier = b
                }
                }, failHandler: { error in
                    XHProgressHUD.showError("图片识别失败，请重新上传!")
            })
        }
        
        present(vc!, animated: true, completion: nil)
    }
    
    @IBAction func drivingLicensePage(_ sender: UIButton) {
        let vc = AipGeneralVC.viewController { [weak self] image in
            
            guard let self = self else {
                return
            }
            
            guard let image = image else {
                XHProgressHUD.showError("图片为空")
                return
            }
            
            self.dismiss(animated: true, completion: nil)
            
            sender.setImage(image, for: .normal)
            
            //上传图片
            User.uploadFile(image) { [weak self] imagePath in
                self?.drivingLicensePageImg = imagePath
            }
        }
        
        present(vc!, animated: true, completion: nil)
    }
    
    @IBAction func submit(_ sender: UIButton) {
        guard let dl = drivingLicenseImg else {
            self.showError("请您上传驾驶证正面照片(1007)")
            return
        }
        
        guard let dlp = drivingLicensePageImg else {
            self.showError("请您上传驾驶证副页照片(1008)")
            return
        }
        
        guard let s = numberTextField.text, !s.isEmpty else {
            self.showError("请填写驾驶证档案编号(1009)")
            return
        }
        
        guard s.count == 12 else {
            self.showError("请输入正确档案编号(1009)")
            return
        }
        
        XHProgressHUD.showStatusInfo("正在识别认证中")
        User.AuthenticationDrivingLicense(
            drivingLicenseImg: dl,
            drivingLicensePageImg: dlp,
            drivingLicenseFn: s,
            success: { [weak self] in
                if let self = self {
                    XHProgressHUD.dismiss()
                    if let user = User.info() {
                        XHProgressHUD.showSuccess("实名认证成功")
                        
                        user.certFlag = 2
                        
                        User.saveUserInfo(user)
                        self.slipViewController?.menuViewController?.refresh()
                        //认证成功
                        self.performSegue(withIdentifier: "attestationSuccessSegue", sender: nil)
                    }
                }
        }) { [weak self] error in
            XHProgressHUD.dismiss()
            if let self = self, let user = User.info() {
                if error.code == 2023 {
                    user.certStep = 2
                    User.saveUserInfo(user)
                    self.performSegue(withIdentifier: "attestationningSegue", sender: nil)
                } else {
                    self.showError(error)
                }
            }
        }
    }
    
    @IBAction func back(_ sender: UIButton) {
        navigationController?.popToRootViewController(animated: true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
